<?php

namespace App\Services\Admin;

use App\Lib\Util\ErrorCode;
use App\Models\Admin\UserModel;
use Illuminate\Support\Facades\Redis;

/**
 * Class UserService
 * @package App\Services\Admin
 */
class UserService
{

    const KEY_USER_AUTH = 'userAuth';
    private $redis;
    private $UserModel;

    public function __construct(UserModel $UserModel)
    {
        $this->UserModel = $UserModel;
        $this->redis = Redis::connection();
    }

    /**
     * 获取登录信息
     * @return array|mixed
     */
    public function getLoginInfo()
    {
        $token = request()->header('token');
        if (!empty($token)) {
            $info = Redis::get($token);
            if (!empty($info)) {
                $info = json_decode($info, true);
            }
        }
        return $info ?? [];
    }
    /**
     * 校验是否登陆
     * @param bool $token
     * @return array|mixed
     * @throws \Exception
     */
    public function checkLogin($token = '')
    {
        if (empty($token)) {
            throw new \Exception('用户未登录', ErrorCode::UNLOGIN);
        }
        $user = $this->redis->get($token);
        if (empty($user)) {
            throw new \Exception('用户未登录', ErrorCode::UNLOGIN);
        }
        //根据token获取登陆信息
        if (empty($user)) {
            throw new \Exception('用户未登录', ErrorCode::UNLOGIN);
        }
        return $user;
    }
    /**
     * 登陆
     * @param $arrRequest
     * @return array
     * @throws \Exception
     */
    public function Login($arrRequest)
    {
//        if (env('APP_ENV') == 'local') {
//            //测试登陆信息
//            $user = config('tmpuser');
//        } else {
            if (empty($arrRequest['mobile'])) {
                throw new \Exception('', ErrorCode::PARAMS_ERROR);
            }
            if (empty($arrRequest['password'])) {
                throw new \Exception('', ErrorCode::PARAMS_ERROR);
            }
            $user['mobile']= $arrRequest['mobile'];
            $user['password']= $arrRequest['password'];
//        }

      return $this->setUser($user['mobile'],$user['password']);
    }

    /**
     * 校验账号信息
     * @param $mobile
     * @param $passportId
     * @return array
     * @throws \Exception
     */
    public function setUser($mobile, $passportId)
    {
        //获取用户信息
        $info = $this->UserModel->query()->where('mobile', $mobile)->with(
          ['RoleInfo:name']
        )->first();
        //用户不存禁止登陆
        if (empty($info)) {
            throw new \Exception('非法用户，不能登陆');
        }
        if($info->password != $passportId){
          throw new \Exception('非法用户，不能登陆');
        }
        //用户是否激活
        if ($info->status != UserModel::STATUS_ACTIVE) {
            throw new \Exception('用户状态异常，不能登陆' . $info->status, \App\Lib\Util\ErrorCode::UNAUTHORIZED);
        }
        $info->roles = $info->RoleInfo->pluck('name')->toArray();
        unset($info->RoleInfo);
        //获取token
        $info->token = self::getToken($info);
        return $info->toArray();
    }


  /**
   * 获取token
   * @param array $param
   * @return string
   */
    public function getToken($param = [])
    {
        $token = md5(time() . $param['mobile']);
        $this->redis->setex($token, 86400, json_encode($param, JSON_UNESCAPED_UNICODE));
        return $token;
    }

  /**
   * @param string $token
   * @return mixed
   * @throws \Exception
   */
  public function getUserInfo($token = '')
  {
    $arrData = $this->redis->get($token);
    $arrData = json_decode($arrData,true);
    $arrData['rulesList'][]= array(
      'path'=>'/tab',
      'component'=>'Layout',
      'name'=>'Layout',
      'children'=>array(
        array(
          'path'=>'index',
//          'component'=>'Layout',
          'component'=>'tab/index',
          'name'=>'Tab',
          'meta'=>array(
            'title'=>'tab组件',
            'noCache'=>'true'
//            'icon'=>'tab'
          ),
        )
      ),
    );
    return $arrData;
  }

}
